from src.utils.odoorpc import ODOO

import random


def get_values(sensor_id, date1, date2):
    Model = odoo.env['iot.value']
    fields = [
        'etl_timestamp', 'time',
        'sensor_id',
        # 'latitude', 'longitude', 'depth',
        'value'
        # 'code', 'name',
        # 'project_id', 'gateway_id', 'device_id', 'sensor_type_id',

    ]

    order = 'etl_timestamp'
    domain1 = [('sensor_id', '=', sensor_id)]
    domain2 = [('time', '<', date2), ('time', '>=', date1), ]
    domain = domain1 + domain2
    values = Model.search_read(domain, fields, order=order)
    return values


def get_sensor(sensor_id):

    Sensor = odoo.env['iot.sensor']

    sensor_fields = [
        'name',
        'code',
        'device_id',
        'gateway_id',
        'project_id',
        'latitude',
        'longitude',
        'sensor_type_id',
        'depth',
    ]

    res = Sensor.search_read([('id', '=', sensor_id)], sensor_fields)

    rec = res[0]

    return {
        'sensor_id': rec['id'],
        'name': rec['name'],
        'code': rec['code'],
        'device_id': rec['device_id'][0],
        'gateway_id': rec['gateway_id'][0],
        'project_id': rec['project_id'][0],
        'sensor_type_id': rec['sensor_type_id'][0],
        'latitude': rec['latitude'],
        'longitude': rec['longitude'],
        'depth': rec['depth'],
    }


# {'id': 211, 'name': '000000000003-01', 'code': '000000000003-01',
# 'device_id': [103, '000000000003'], 'gateway_id': [53, '000000000002'],
#  'project_id': [65, 'dsp'],
# 'latitude': 40.051190000000005, 'longitude': 116.29457000000001,
# 'sensor_type_id': [2, 'Moisture'], 'depth': 0}


def get_new_values(sensor_id, old_sensor_id, date1, date2):
    values = get_values(old_sensor_id, date1, date2)
    sensor = get_sensor(sensor_id)
    # print(sensor)

    values2 = [dict({
        'etl_timestamp': val['etl_timestamp'],
        'time':val['time'],
        'value': val['value'] + random.randint(-100, 100),
    }, **sensor)for val in values]

    return values2


def set_values(sensor_id, old_sensor_id, date1, date2):

    values = get_new_values(sensor_id, old_sensor_id, date1, date2)
    print(values)

    Model = odoo.env['iot.value']

    for vals in values:
        res = Model.update_or_create(vals)
        print(res)


if __name__ == '__main__':
    pass

    host = 'http://106.13.191.63:8069'
    db = 'TheWell'
    user = 'xxmcu@sohu.com'
    password = '123456'

    odoo = ODOO(host, db)
    res = odoo.login(user, password)
    print(res)

    date1 = '2020-12-11'
    date2 = '2020-12-12'
    old_sensor_id = 207
    sensor_id = 211
    set_values(sensor_id, old_sensor_id, date1, date2)
